<template>
  <!--开票审请-->
  <BasicModal :title="getTitle" :width="'95%'" @register="registerModal" @ok="handleSubmit" @cancel="handleClose"
              :destroyOnClose="true" :canFullscreen="false" :centered="true"
              :bodyStyle="{height:'calc(100vh - 120px)', overflowY:'hidden'}"
  >
    <!-- 开票申请 -->
    <div class="jeecg-basic-table jeecg-basic-table-form-container" style="margin-top: -10px">
      <a-form @keyup.enter.native="searchQuery">
        <a-row :gutter="8" type="flex">
          <a-col flex="145px">
            <a-form-item label="部门" :label-col="{ style: { width: '55px' } }" :wrapper-col="{ span: 18 }">
              <JDictSelectTag
                v-model:value="queryParam.ddlxIds"
                mode="multiple"
                dictCode="ddlxType@ddlxUser"
                placeholder="全部"
                :maxTagCount="0"
                :getPopupContainer="(node) => node.parentNode"
                :dropdownStyle="{ width: '120px', overflow: 'auto' }"
                :dropdownMatchSelectWidth="false"
              />
            </a-form-item>
          </a-col>

          <a-col flex="120px">
            <a-form-item label="状态" :label-col="{ style: { width: '40px' } }" >
              <a-select v-model:value="queryParam.invoiceFlowStat" placeholder="全部" :showArrow="false" :allowClear="true">
                <a-select-option value="0">未申请</a-select-option>
                <a-select-option value="1">已申请</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col flex="360px">
            <a-form-item label="" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ style: { width: '250px' } }">
              <a-select v-model:value="queryParam.sdate" default-value="0" id="today" style="width: 90px; margin-right: 5px" >
                <a-select-option value="0">出团日期</a-select-option>
                <a-select-option value="1">收付日期</a-select-option>
              </a-select>
              <a-date-picker
                v-model:value="queryParam.beginDate"
                :disabled-date="disabledStartDate"
                valueFormat="YYYY-MM-DD"
                placeholder=""
                style="width: 110px"
              /> ~
              <a-date-picker
                v-model:value="queryParam.endDate"
                :disabled-date="disabledEndDate"
                valueFormat="YYYY-MM-DD"
                placeholder=""
                style="width: 110px"
              />
            </a-form-item>
          </a-col>

          <a-col flex="260px">
            <a-form-item label="收支账户" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ style: { width: '130px' } }">
              <JDictSelectTag
                placeholder=""
                v-model:value="queryParam.bankId"
                dictCode="chee_bank,djm,id@ddlxBank"
                :getPopupContainer="(node) => node.parentNode"
                :dropdownStyle="{ width: '190px', overflow: 'auto' }"
                :dropdownMatchSelectWidth="false"
                :showArrow="false"
                :maxTagTextLength="20"
              />
            </a-form-item>
          </a-col>

          <a-col flex="170px">
            <a-form-item label="订单号" :label-col="{ style: { width: '55px' } }">
              <a-input placeholder="" v-model:value="queryParam.orderId" ></a-input>
            </a-form-item>
          </a-col>

          <a-col flex="auto" style="float:right; width:90px; margin-right: 0px;">
          <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
            <a-button type="primary" preIcon="ant-design:search" @click="searchQuery" class="mr-10px">查询</a-button>
          </span>
          </a-col>
        </a-row>

        <a-row :gutter="8" type="flex">
          <a-col flex="145px">
            <a-form-item label="操作人" :label-col="{ style: { width: '55px' } }">
              <JDictSelectTag
                v-model:value="queryParam.userIds"
                mode="multiple"
                dictCode="sys_user,realname,id@authUser"
                placeholder="全部"
                :maxTagCount="0"
                :dropdownStyle="{ width: '120px', overflow: 'auto' }"
                :dropdownMatchSelectWidth="false"
                :allowClear="true"
              />
            </a-form-item>
          </a-col>

          <a-col flex="120px">
            <a-form-item label="类型" :label-col="{ style: { width: '40px' } }" >
              <a-select v-model:value="queryParam.sflx" placeholder="全部" :showArrow="false" :allowClear="true">
                <a-select-option value="1">收入</a-select-option>
                <a-select-option value="2">支出</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col flex="200px">
            <a-form-item label="金额" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 17 }">
              <a-input type="text" v-model:value="queryParam.beginJe" style="width: 60px" @blur="onBlur"/> -
              <a-input type="text" v-model:value="queryParam.endJe"  style="width: 60px"/>
            </a-form-item>
          </a-col>

          <a-col flex="250px">
            <a-form-item label="收款单位" :label-col="{ style: { width: '65px' } }">
              <a-input placeholder="" v-model:value="queryParam.dwmc" ></a-input>
            </a-form-item>
          </a-col>

          <a-col flex="280px">
            <a-form-item label="备注" :label-col="{ style: { width: '65px' } }">
              <a-input placeholder="" v-model:value="queryParam.bz" ></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!--引用表格 :rowSelection="rowSelection"-->
    <BasicTable @register="registerTable" :loading="loading" :rowSelection="rowSelection"></BasicTable>
    <!-- table区域-end v-auth="'business:delete'"-->

    <SelectModal @register="registerSelectModal" @success="searchQuery"></SelectModal>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive, watch, toRaw } from "vue";
import { BasicColumn, BasicTable } from "/@/components/Table";
import { useListPage } from "/@/hooks/system/useListPage";
import { BasicModal, useModal, useModalInner } from "/@/components/Modal";
import { openAccountList } from "../types/invoice.api";
import { useMessage } from "/@/hooks/web/useMessage";
import { momentSearchQueryDate } from "/@/utils/dateUtil";
import { render } from "/@/utils/common/renderUtils";
const { createMessage: $message } = useMessage();
import moment from 'dayjs'
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import SelectModal from "/@/views/full/invoice/modules/openAccountGridSelectModal.vue";

const isUpdate = ref(true);
//标题
const getTitle = computed(() => (queryParam.sflx == '1' ? '收入数据' : '支出数据'));
const $businessId = ref("");
//初始化 -------------------------------------------------------------
//定义查询表单，查询条件
const queryParam = reactive<any>({
  sflx: '1',
  sdate: '0',
  beginDate : momentSearchQueryDate('sub', 60),
  endDate: momentSearchQueryDate('add', 0),
});
let type = ref("");
//表单赋值
const [registerModal, { closeModal }] = useModalInner(async (data) => {
  $businessId.value = data.businessId;
  queryParam.type   = data.type; //registerOpenAccountGird
  type.value        = data.type;
  if (data.type == 'open') {
    queryParam.sflx = '1'
  } else if (data.type == 'back') {
    queryParam.sflx = '2'
  } else {

  }
});

//限制查询日期，开始日期不能大于结束日期
function disabledStartDate(beginDate) {
  const endDate = queryParam.endDate;
  if (!beginDate || !endDate) {
    return false;
  }
  return beginDate.valueOf() > moment(endDate).valueOf()
}

function disabledEndDate(endDate) {
  const beginDate = queryParam.beginDate;
  if (!endDate || !beginDate) {
    return false;
  }
  return moment(beginDate).valueOf() > endDate.valueOf();
}

//--金额-------------------------------------------------------
// '.' at the end or only '-' in the input box.
const onBlur = (inputValue) => {

};

//初始化 -------------------------------------------------------------
function searchQuery() {
  setProps({searchInfo:toRaw(queryParam)});
  reload()
}

function searchReset() {
  Object.assign(queryParam, {ddlxIds: '', ddzt: '', ywlx: ''});
  reload();
}

function handleSummary(tableData: Recordable[]) {
  redoHeight();
  const res = getRawDataSource()
  return res.summary || [];
}

//订单列表
const statusFmt = ({text}: { text: any }) => {
  let color = '';
  let value = '';
  if (text == '1') {
    color = 'green'
    value = '已申请'
  } else {
    color = 'red'
    value = '未申请'
  }
  return render.renderTag(value, color)
}

const dwmc = ({ text, record }) => {
  if (record.sflx == "1") {
    text = record.customerPathName
  } else {
    text = record.cooperatorPathName
  }
  if (!text) {
    return "";
  } else {
    return text;
  }
};

//订单列表 - 表头
const columns: BasicColumn[] = [
  { title: "状态", align: "center", dataIndex: "invoiceStat", width: 55, customRender: statusFmt },
  { title: "部门", align: "center", dataIndex: "ddlx", width: 60, customRender:({text}) => render.renderDict(text, 'ddlxType') },
  { title: "订单号", align: "center", dataIndex: "orderId", width: 80, className:"text-red-500" },
  { title: "收付单位", align: "left", dataIndex: "dwmc", width: 190, customRender: dwmc },
  { title: "收入", align: "right", dataIndex: "skje", width: 80, className:"text-red-500" },
  { title: "支出", align: "right", dataIndex: "fkje", width: 80, className:"text-green-500" },
  { title: "收付时间", align: "center", dataIndex: "sfsj", format: "date|YYYY-MM-DD", width: 80},
  { title: "银行", align: "left", dataIndex: "djm", width: 120 },
  { title: "备注", align: "left", dataIndex: "bz", width: 200 },
  { title: "操作人", align: "center", dataIndex: "lrr", width: 55 },
]

// 列表页面公共参数、方法
const loading     = ref<boolean>(false);
const dataSource  = ref<any[]>([]);
const summaryData = ref<any[]>([]);
const {prefixCls, tableContext} = useListPage({
  designScope: 'open-account-grid',
  tableProps: {
    api: openAccountList,
    columns: columns,
    showIndexColumn: false,    //行号
    clickToRowSelect: true,    //点击选择
    showActionColumn: false,
    showTableSetting: false,
    useSearchForm: false,
    showSummary: false,
    resizeHeightOffset: 65,
    beforeFetch: (params) => Object.assign(params, unref(queryParam)),
  },
})

// 注册table数据
const [registerTable, {reload, setProps, getRawDataSource, setSelectedRowKeys, redoHeight}, {rowSelection, selectedRowKeys, selectedRows}] = tableContext

// 开票申请 - 勾选 -------------------------
const [registerSelectModal, { openModal: openSelectModal }] = useModal();
function handleSubmit() {
  //1、获取被选中的行信息
  let rows = selectedRows.value;
  if (rows.length <= 0) {
    $message.warning("请勾选")
    return false
  }

  //2、判断选中的单位是否是同一家
  var pId = [], ids = ''
  for (var i = 0; i < rows.length; i++) {
    pId.push(rows[i].coopId)
    if (i == 0) {
      ids = rows[i].id;
    } else {
      ids = ids + "," + rows[i].id;
    }
  }
  if (pId.length > 0) {
    pId = pId.sort()
    for (var i = 0; i < pId.length - 1; i++) {
      if (pId[i] != pId[i + 1]) {
        $message.warning('请选择同一家供应商，进行付款款申请审核操作！')
        return false
      }
    }
  }

  var params = {ids:ids, businessId: $businessId.value, type: type.value}
  //console.info("params@@@", queryParam)
  openSelectModal(true, params);
}

const emit = defineEmits(['success', 'register']);
function handleClose() {
  console.info("handleClose")
  emit("success");
}
</script>

<style lang="less" scoped>

</style>
